`<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->

<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-button-group>
        <el-button
          type="primary"
          icon="plus"
          @click="handlerAdd"
        >{{ $t('add') }}
        </el-button>
        <el-button
          type="primary"
          icon="edit"
          @click="handlerEdit"
        >{{ $t('edit') }}
        </el-button>
        <el-button
          type="primary"
          icon="delete"
          @click="handleDelete"
        >{{ $t('delete') }}
        </el-button>
      </el-button-group>
    </div>

    <el-row>
      <el-col
        :span="8"
        style="margin-top:15px;"
      >
        <el-tree
          class="filter-tree"
          :data="treeData"
          node-key="id"
          highlight-current
          :props="defaultProps"
          :filter-node-method="filterNode"
          default-expand-all
          @node-click="getNodeData"
        />
      </el-col>
      <el-col
        :span="16"
        style="margin-top:15px;"
      >
        <el-card class="box-card">
          <el-form
            ref="form"
            :label-position="labelPosition"
            label-width="150px"
            :rules="rules"
            :model="form"
          >
            <el-form-item
              :label="$t('parent')+$t('node')"
              prop="parentId"
            >
              <el-input
                v-model="form.parentId"
                :disabled="formEdit"
                :placeholder="$t('parent')+$t('node')"
              />
            </el-form-item>
            <el-form-item
              v-if="formEdit"
              :label="$t('id')"
              prop="deptId"
            >
              <el-input
                v-model="form.deptId"
                :disabled="formEdit"
                :placeholder="$t('id')"
              />
            </el-form-item>
            <el-form-item
              :label="$t('name')"
              prop="name"
            >
              <el-input
                v-model="form.name"
                :disabled="formEdit"
                :placeholder="$t('name')"
              />
            </el-form-item>
            <el-form-item
              :label="$t('rankNumber')"
              prop="orderNum"
            >
              <el-input
                v-model="form.sort"
                type="number"
                :disabled="formEdit"
                :placeholder="$t('rankNumber')"
              />
            </el-form-item>
            <el-form-item v-if="formStatus == 'update'">
              <el-button
                type="primary"
                @click="update"
              >{{ $t('edit') }}
              </el-button>
              <el-button @click="onCancel">{{ $t('cancel') }}</el-button>
            </el-form-item>
            <el-form-item v-if="formStatus == 'create'">
              <el-button
                type="primary"
                @click="create"
              >{{ $t('save') }}
              </el-button>
              <el-button @click="onCancel">{{ $t('cancel') }}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  deleteCompanyDept,
  getCompanyDept,
  insertCompanyDept,
  treeCompanyDept,
  updateCompanyDept
} from '@/api/auth/authCompanyDeptApi'
import { mapGetters } from 'vuex'
import { getCompanyId } from '@/util/storage'
import { successNotice } from '@/util/common'

var validatedeptname = (rule, value, callback) => {
  getCompanyDept({
    'deptName': value,
    companyId: getCompanyId()
  }).then(res => {
    const { data } = res
    if (window.boxType === 'edit') callback()
    if (data !== null) {
      callback(new Error('exixt'))
    } else {
      callback()
    }
  })
}

export default {
  name: 'CompanyDept',
  data() {
    return {
      list: null,
      total: null,
      formEdit: true,
      formAdd: true,
      formStatus: '',
      showElement: false,
      typeOptions: ['0', '1'],
      methodOptions: ['GET', 'POST', 'PUT', 'DELETE'],
      menuTitle: this.$t('function'),
      listQuery: {
        name: undefined,
        companyId: getCompanyId()
      },
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      rules: {
        parentId: [
          { required: true, message: '请输入父级节点', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请输入节点编号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { validator: validatedeptname, trigger: 'blur' }
        ],
        orderNum: [
          { required: false, message: '排序值', trigger: 'blur' }
        ]
      },
      labelPosition: 'right',
      form: {
        name: undefined,
        orderNum: undefined,
        parentId: undefined,
        deptId: undefined,
        companyId: getCompanyId()
      },
      currentId: 0
    }
  },
  created() {
    this.treeCompanyDept()
  },
  computed: {
    ...mapGetters([
      'elements',
      'permissions'
    ])
  },
  methods: {
    treeCompanyDept() {
      treeCompanyDept(this.listQuery).then(res => {
        const { data } = res
        this.treeData = data
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getNodeData(data) {
      if (!this.formEdit) {
        this.formStatus = 'update'
      }
      getCompanyDept({
        'deptId': data.id,
        companyId: this.form.companyId
      }).then(res => {
        const { data } = res
        data.companyId = getCompanyId()
        this.form = data
      })
      this.currentId = data.id
      this.showElement = true
    },
    handlerEdit() {
      if (this.form.deptId) {
        this.formEdit = false
        this.formStatus = 'update'
      }
    },
    handlerAdd() {
      this.resetForm()
      this.formEdit = false
      this.formStatus = 'create'
    },
    handleDelete() {
      const that = this
      this.$confirm(this.$t('deletePrompt'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        deleteCompanyDept({ 'deptId': this.currentId }).then(() => {
          this.treeCompanyDept()
          this.resetForm()
          this.onCancel()
          successNotice(that)
        })
      })
    },
    update() {
      const that = this
      this.$refs.form.validate((valid) => {
        if (!valid) return
        updateCompanyDept(this.form).then(() => {
          this.treeCompanyDept()
          successNotice(that)
        })
      })
    },
    create() {
      const that = this
      this.$refs.form.validate((valid) => {
        if (!valid) return
        insertCompanyDept(this.form).then(() => {
          this.treeCompanyDept()
          successNotice(that)
        })
      })
    },
    onCancel() {
      this.formEdit = true
      this.formStatus = ''
    },
    resetForm() {
      this.form = {
        parentId: this.currentId,
        companyId: getCompanyId()
      }
    }
  }
}
</script>

